package com.kate.service.impl;

import com.kate.entity.UserInfo;
import com.kate.mapper.UserInfoMapper;
import com.kate.service.IUserInfoService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileNotFoundException;

/**
 * 声明式事务
 */
@Component
public class UserInfoServiceImpl5 implements IUserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Transactional(rollbackFor = FileNotFoundException.class)
    public boolean zz(int from, int to, int money) throws FileNotFoundException {
       return zzOptional(from,to,money);
    }

    private boolean zzOptional(int from, int to, int money) throws  FileNotFoundException {
        // 一,==============旺财的钱减少200==============
        // 1.1查询旺财有多少钱
        UserInfo wc = userInfoMapper.selectByPrimaryKey(from);
        System.out.println(wc);
        // 1.2扣旺财有300
        int result = 0;
        if(wc!=null&&wc.getMoney()>money) {
            wc.setMoney(wc.getMoney() - money);
            result = userInfoMapper.updateByPrimaryKey(wc);
        }
        // ==============二,来福的钱增加200==============
        // 1.1查询旺财有多少钱
        UserInfo lf = userInfoMapper.selectByPrimaryKey(to);
        System.out.println(lf);
        // 1.2扣旺财有300
        int result2 = 0;
        if (lf != null) {
            lf.setMoney(lf.getMoney() + money);
            result2 = userInfoMapper.updateByPrimaryKey(lf);
        }
        // ==============最后的结果==============
        if (result <= 0 || result2 <= 0) {
            throw new FileNotFoundException("转账失败");
        }
        return true;
    }


}